class Solution {
    public int index;
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return buildTreeChild(preorder,inorder,0,inorder.length-1);
    }
    private TreeNode buildTreeChild(int[]preorder,int[]inorder,int inbegin,int inend){
        if(inbegin>inend){
            return null;
        }
        TreeNode root=new TreeNode(preorder[index]);
        int rootIndex=findrootIndex(inorder,inbegin,inend,preorder[index]);
        if(rootIndex==-1){
            return null;
        }
        index++;
        root.left=buildTreeChild(preorder,inorder,inbegin,rootIndex-1);
        root.right=buildTreeChild(preorder,inorder,rootIndex+1,inend);
        return root;
    }

    private int findrootIndex(int[] inorder,int inbegin,int inend,int key){
        for(int i=inbegin;i<inend;i++){
            if(inorder[i]==key){
                return i;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        Solution solution=new Solution();
        int[] preorder={3,9,20,15,7};
        int[] inorder={9,3,15,20,7};
        TreeNode root=solution.buildTree(preorder,inorder);

    }
}